import { Popconfirm, Table, Tag, Space, Card, Form, Button, Input, message } from 'antd'
import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '@/store'
import { http, copyStr } from '@/utils'
import Addorupdatamodal from './components/Addorupdatamodal'
import Configmodal from './components/Configmodal'
import Configlistmodal from './components/Configlistmodal'
import Setvariety from './components/Setvariety'
import './index.scss'

const Warningroup = () => {
    // 预警组列表管理 统一管理数据 将来修改给setArticleData传对象
    const [warningroupData, setWarningroupData] = useState({
        list: [],// 预警组列表
        count: 0 // 预警组数量
    })
    const [warningroupDataRow, setWarningroupDataRow] = useState({})
    const { loginStore } = useStore()
    const [dictData, setDictData] = useState({ 1000: [] })
    const [params, setParams] = useState({
        pageNum: 1,
        pageSize: 20
    })

    /* 表单筛选功能实现 */
    const onSeach = (values) => {
        const _params = { ...values }
        // 修改params数据 引起接口的重新发送 对象的合并是一个整体覆盖 改了对象的整体引用
        setParams({
            ...params,
            ..._params,
            pageNum: 1,
        })
    }

    // 翻页实现
    const pageChange = (page, pageSize) => {
        setParams({
            ...params,
            pageSize: pageSize,
            pageNum: page
        })
    }

    // 添加修改预警组
    const childAddorConfigRef = React.createRef()
    const handleAddmodal = (row) => {
        childAddorConfigRef.current.openModalOpen(row)
    }
    const changeAddorupdata = (msg) => {
        console.log(msg)
        setParams({ ...params, pageNum: 1 })
    }
    const delWarningroup = async (data) => {
        const res = await http.post('/alarm/deliversign/deleteAlarmGroupInfo', { groupId: data.id })
        message.success(res.body)
        setParams({ ...params })
    }

    // 预警组预警配置model
    const childConfigRef = React.createRef()
    const showAddorConfigModalOpen = (data) => {
        childConfigRef.current.openModalOpen(data)
    }
    const changeConfig = (msg) => {
        console.log(msg)
        setParams({ ...params, pageNum: 1 })
    }

    // 预警组配置列表model
    const childConfiglist = React.createRef()
    const showConfigModalOpen = (data) => {
        childConfiglist.current.openModalOpen(data)
    }
    const changeConfiglist = (msg) => {
        console.log(msg)
        setParams({ ...params })
    }

    useEffect(() => {
        const getList = async () => {
            setWarningroupData({ list: [], count: 0 })
            const res = await http.post('/alarm/deliversign/findAlarmGroupInfoByPage', { userId: loginStore.userId, ...params })
            console.log('预警组列表-', res.body)
            const { list, total } = res.body
            setWarningroupData({
                list: list,
                count: total
            })
        }
        const getDicfig = async () => {
            const res = await http.post('/alarm/deliversign/getDicConfig', {
                userId: loginStore.userId,
                dictIds: [1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009]
            })
            setDictData(res.body)
            console.log('字典-', res.body)
        }
        if (dictData[1000].length) {
            getList()
        } else {
            getDicfig()
        }
    }, [params, dictData, loginStore])

    // 预警组品种 1 手动更新 2 自动更新
    const formatStatus = (type) => {
        const TYPES = {
            1: <Tag>手动更新</Tag>,
            2: <Tag>自动更新</Tag>
        }
        return TYPES[type]
    }


    // 下属品种
    const navigate = useNavigate()
    const goVariety = (data) => {
        navigate(`/variety?groupId=${data.id}&groupName=${data.groupAlarmName}`)
    }
    // 设置品种
    const [showVarietymodal, setShowVarietymodal] = useState(false)
    const setVariety = (data) => {
        setShowVarietymodal(true)
        setWarningroupDataRow(data)
    }
    const changeVarietyModal = (val) => {
        setShowVarietymodal(val)
        setParams({ ...params })
    }
    const getGroupIdText = async (data) => {
        const res = await http.post('/alarm/deliversign/findAlarmFeatureByGroupIdText', { groupId: data.id })
        message.success(res.msg)
        copyStr(res.body)
    }

    const columns = [
        {
            title: '编号',
            dataIndex: 'id',
            width: 100,
        },
        {
            title: '预警组名称',
            dataIndex: 'groupAlarmName',
            minWidth: 220
        },
        {
            title: '预警组品种',
            dataIndex: 'groupType',
            minWidth: 220,
            render: data => formatStatus(data)
        },
        {
            title: '备注',
            dataIndex: 'mark'
        },
        {
            title: '创建用户',
            dataIndex: 'userName'
        },
        {
            title: '操作',
            render: data => {
                return (
                    <Space size="middle">
                        <Button size="small" onClick={() => showConfigModalOpen(data)}>配置列表</Button>
                        <Button size="small" onClick={() => showAddorConfigModalOpen(data)}>添加</Button> |
                        <Button size="small" disabled={!data.subFeatureCount} onClick={() => goVariety(data)}>下属品种 （{data.subFeatureCount}）</Button>
                        <Button size="small" disabled={!data.subFeatureCount} onClick={() => getGroupIdText(data)}>导出品种</Button>
                        <Button size="small" disabled={+loginStore.userId !== data.createdBy || data.groupType === 2} onClick={() => setVariety(data)}  >添加品种</Button> |
                        <Button size="small" disabled={+loginStore.userId !== data.createdBy} onClick={() => handleAddmodal(data)}>编辑</Button>
                        <Popconfirm
                            title={`确认删除“${data.groupAlarmName}”这个预警组吗？`}
                            onConfirm={() => delWarningroup(data)}
                            okText="确认"
                            cancelText="取消"
                            disabled={+loginStore.userId !== data.createdBy}
                        >
                            <Button size="small" disabled={+loginStore.userId !== data.createdBy}>删除</Button>
                        </Popconfirm>
                    </Space>
                )
            },
            fixed: 'right'
        }
    ]
    return (
        <div>
            <Card title="预警组列表">
                <Form
                    onFinish={onSeach}
                    layout='inline'
                >

                    <Form.Item label="预警组名称" name="groupAlarmName" >
                        <Input
                            allowClear
                            placeholder='请输入预警组名称'
                            style={{ width: 200 }}
                        />
                    </Form.Item>
                    <Form.Item label="创建用户" name="userName" >
                        <Input
                            allowClear
                            placeholder='请输入用户名称'
                            style={{ width: 200 }}
                        />
                    </Form.Item>
                    <Form.Item label="备注" name="mark" >
                        <Input
                            allowClear
                            placeholder='请输入关键字'
                            style={{ width: 200 }}
                        />
                    </Form.Item>
                    <Form.Item >
                        <Button type="primary" htmlType="submit">
                            查询
                        </Button>
                        <Button type="primary" style={{ marginLeft: 20 }} onClick={() => handleAddmodal()}>
                            添加
                        </Button>
                    </Form.Item>
                </Form>
                <Table
                    style={{ marginTop: 20 }}
                    size='middle'
                    rowKey="id"
                    columns={columns}
                    dataSource={warningroupData.list}
                    pagination={
                        {
                            size: 'default',
                            showQuickJumper: true,
                            showSizeChanger: true,
                            pageSize: params.pageSize,
                            onChange: pageChange,
                            showTotal: (total, range) => `共 ${total} 条`,
                            total: warningroupData.count,
                            current: params.pageNum
                        }
                    }
                    bordered
                />
            </Card >
            <Addorupdatamodal onRef={childAddorConfigRef} changeAddorupdata={changeAddorupdata}></Addorupdatamodal>
            <Configmodal onRef={childConfigRef} changeConfig={changeConfig} dictData={dictData}></Configmodal>
            <Configlistmodal onRef={childConfiglist} changeConfiglist={changeConfiglist} dictData={dictData}></Configlistmodal>
            <Setvariety showVarietymodal={showVarietymodal} warningroupDataRow={warningroupDataRow} changeVarietyModal={changeVarietyModal}></Setvariety>
        </div >
    )
}
export default Warningroup